package com.boe.common.base.jpa;

import com.boe.common.util.ClassUtil;
import com.boe.common.util.StringUtil;
import lombok.SneakyThrows;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.GUIDGenerator;

import java.io.Serializable;

public class BoeIdGenerator extends GUIDGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object entity) throws HibernateException  {
        //如果主键有值，则用实体自带的主键值;否则使用guid生成策略

            Object id= ClassUtil.getPrivatePropertyValue(entity, "id");
            if (id instanceof String) {
                String idStringValue = (String) id;
                if (StringUtil.hasValue(idStringValue)) {
                    return idStringValue;
                }
            }

        return super.generate(session, entity);
    }
}